<template>
  <div id="workItemCompletionTrend" :style="myChartStyle" class="echart"></div>
</template>

<script>
import * as echarts from "echarts";

export default {
  name: "workItemCompletionTrend",
  props: {
    works: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      myChartStyle: { float: "left", width: "100%", height: "320px" }
    };
  },
  watch: {
    works: {
      handler() {
        this.initEcharts();
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    formatDate(date) {
      const d = new Date(date);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0');
      const day = String(d.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    getRecentDates(n = 10) {
      const result = [];
      const today = new Date();
      for (let i = n - 1; i >= 0; i--) {
        const d = new Date(today);
        d.setDate(today.getDate() - i);
        result.push(this.formatDate(d));
      }
      return result;
    },
    initEcharts() {
      const chartDom = document.getElementById("workItemCompletionTrend");
      if (!chartDom) return;
      const myChart = echarts.init(chartDom);

      const dateLabels = this.getRecentDates(10);
      const completedSeries = [];
      const uncompletedSeries = [];
      dateLabels.forEach(currentDateStr => {
        const currentDate = new Date(currentDateStr);
        // 累计完成数：所有 completedAt ≤ 当前日期 且 status === "3"
        const completed = this.works.filter(w => {
          console.log(w);
          if (w.status === "completed"|| w.status === "close") {
            const completedDate = new Date(w.completedAt);
            console.log(completedDate,w.completedAt);
            return completedDate <= currentDate;
          }
          return false;
        }).length;
        completedSeries.push(completed);
        uncompletedSeries.push(this.works.length-completed);
      });
      console.log(completedSeries);
      console.log(uncompletedSeries);
      const option = {
        title: {
          text: "工作项完成趋势（累计）"
        },
        tooltip: {
          trigger: "axis"
        },
        legend: {
          data: ["未完成", "已完成"]
        },
        grid: {
          left: "2%",
          right: "2%",
          bottom: "2%",
          containLabel: true
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: dateLabels
        },
        yAxis: {
          type: "value"
        },
        series: [
          {
            name: "未完成",
            type: "line",
            data: uncompletedSeries
          },
          {
            name: "已完成",
            type: "line",
            data: completedSeries
          }
        ]
      };

      myChart.setOption(option);
    }
  }
};
</script>

<style lang="scss" scoped>
</style>
